//
//  RONetworkMngTool.swift
//  健身宝
//
//  Created by hzt on 2017/9/26.
//  Copyright © 2017年 hzt. All rights reserved.
//

import UIKit
let single = RONetworkMngTool()
var SessionID:String?
var dict:NSDictionary! = nil
class RONetworkMngTool: NSObject {
    private lazy var popup = Popup()
    static var shared = RONetworkMngTool()
    private var sessionManager = AFHTTPSessionManager()
    static var SessionID:String!
    class func shareNetworkMngTool() -> RONetworkMngTool {
        
        return single
        
    }
    func RONetwork_Register(_ parameters: NSDictionary, view: UIView, block: @escaping (_ flag: NSString) -> Void) {
        print(parameters)
        //在开始网络加载前任务指示器开始转
        MBProgressHUD.showAdded(to: view, animated: true)
        let afManager = AFHTTPRequestOperationManager()
        afManager.get(RO_Register, parameters:parameters , success: {(oeration: AFHTTPRequestOperation?, responseObject:Any?) in
            
            print(responseObject)
            MBProgressHUD.hide(for: view, animated: true)
            //将返回的字典转换为模型对象
            var test = responseObject as!NSDictionary
            if test.count > 2
            {
                print("success")
                let success = (responseObject as! NSDictionary).object(forKey: "id") as! NSString
                if success != "0"{
                    
//                    let SessionID = (responseObject as! NSDictionary).object(forKey: "sessionid") as! NSString
//                    print(SessionID)
                    print("注册成功")
                    block("1")
                }
                
            }
            else
            {
                print("fail")
                let success = (responseObject as! NSDictionary).object(forKey: "error") as! NSString
                if success == "手机号已被使用"{
                    MBProgressHUD.showDelayHUDToView(view, message: "手机号已被使用")
                    print("手机号已被使用")
                    block("0")
                }
                
                
            }
                    }) { (operation: AFHTTPRequestOperation?, error:Error?) in
            //失败结束转
            MBProgressHUD.hide(for: view, animated: true)
            MBProgressHUD.showDelayHUDToView(view, message: "网络原因注册失败！")
            block("0")
        }
    }
    func RONetwork_Logon(_  parameters:NSDictionary,view:UIView, block:@escaping (_ flag: NSString) -> Void )  {
        
        MBProgressHUD.showAdded(to: view, animated: true)
        
        
        let afManager = AFHTTPRequestOperationManager()
        
        afManager.get(RO_Logon, parameters: parameters, success: {(operation:AFHTTPRequestOperation?,responseObject:Any?) in
            MBProgressHUD.hide(for:view,animated:true)
            
            //直接解析返回值
                                //print(responseObject)
            //                    let userid = (responseObject as! NSDictionary).object(forKey: "userid") as! NSString
            //                    if userid != "0" {
            //                        print("登录成功")
            //                    } else {
            //                        print("登录失败")
            //                    }
            
            
            //let loginModel = LoginModel.logonReturnModelWithDict(responseObject as! NSDictionary)
            //登录成功够保存用户名和密码

            var test = responseObject as!NSDictionary
            if test.count > 2
            {
                print("success")
                let success = (responseObject as! NSDictionary).object(forKey: "id") as! NSString
                if success != "0"{
                    LoginModel.getUserInfo(dict: responseObject as! NSDictionary)
//                    RONetworkMngTool.SessionID = ((responseObject as! NSDictionary).object(forKey: "sessionid") as! NSString) as String!
//                    print(RONetworkMngTool.SessionID)
                    //print(LoginModel.sessionID)
                    print("登录成功")
                    block("1")
                }

            }
            else
            {
                print("fail")
                let success = (responseObject as! NSDictionary).object(forKey: "error") as! NSString
                if success == "用户名或密码不正确"{
                    MBProgressHUD.showDelayHUDToView(view, message: "用户名或密码不正确")
                    print("用户名或密码不正确")
                    block("0")
                }

                
            }
            
        }, failure:  { (Operation:AFHTTPRequestOperation?, error:Error?) in
            
            MBProgressHUD.hide(for:view,animated:true)
            MBProgressHUD.showDelayHUDToView(view, message: "网络原因加载失败")
            block("0")
            
        })
        }
    
    
    func isExits(parameter:NSDictionary,block:@escaping (Bool)->Void){
        post(urlStr: RO_Exit, parameter: parameter) { (json) in
            if let dict = json as? NSDictionary{
                DispatchQueue.main.async {
                    self.popup.appear(title: dict.value(forKey: "error") as! String, action: nil)
                }
            }else{
                let str = json as! String
                if str == "0"{
                    block(true)
                }else{
                    block(false)
                }
            }
        }
        
    }
 
    func joinClub(parameter:NSDictionary,block:@escaping ()->Void){
        post(urlStr: RO_JoinClub, parameter: parameter, block: nil)
        block()
    }
    
    func focusMaster(parameter:NSDictionary,block:@escaping ()->Void){
        post(urlStr: RO_FocusMaster, parameter: parameter, block: nil)
        block()
    }
    
    func creat(parameter:NSDictionary,block:@escaping ()->Void){
        post(urlStr: RO_Create, parameter: parameter, block: nil)
        block()
    }
    
//    func fetchImage(block:@escaping (NSArray)->Void){
//        sessionManager.post(RO_Picture, parameters: nil, constructingBodyWith: nil, success: { (datatask, json) in
//            block(json as! NSArray)
//            print(json)
//        }, failure: nil)
//    }
    
    func fetchImage(block:@escaping (NSArray)->Void){
        sessionManager.post("http://172.24.10.175/workout/api.php/lists/mod/itempos/SessionID/2ul9sj8vlfofj122e1s98048k2/related/1/posid/1", parameters: nil, success: { (datatask, json) in
            block(json as! NSArray)
            print(json)
        }, failure: nil)
    }
    
    func postSharing(parameter:NSDictionary,image:UIImage,block:@escaping ()->Void){
        sessionManager.post(RO_PostPhoto, parameters: parameter, constructingBodyWith: { (fromData) in
            if let data = UIImageJPEGRepresentation(image, 1){
                fromData?.appendPart(withFileData: data, name: "thumb0", fileName: "image.jpeg", mimeType: "image/jpeg")
            }else{
                let data = UIImageJPEGRepresentation(UIImage(named:"placeholder")!,0.1)
                fromData?.appendPart(withFileData: data!, name: "thumb0", fileName: "image.jpeg", mimeType: "image/jpeg")
            }

        }, success: { (task, json) in
            block()
        }) { (task, error) in
            block()
        }

    }

    
    private func post(urlStr:String,parameter:NSDictionary,block:((_ data:Any?)->Void)?){
        let paraArray = NSMutableArray()
        for (key,value) in parameter{
            let str = "\(key)=\(value)"
            paraArray.add(str)
        }
        let body = paraArray.componentsJoined(by: "&")
        var request = URLRequest(url: URL(string: urlStr)!)
        request.httpMethod = "post"
        request.httpBody = body.data(using: String.Encoding.utf8)
        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if data != nil{
                if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers){
                    block!(json)
                }
                else{
                    if let str = String(data: data!, encoding: String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)))){
                        //print(str)
                    }else if let str = String(data: data!, encoding: .utf8){
                       //print(str)
                    }
                }
            }else{
                print("返回为空")
                print(error.debugDescription)
            }
        }
        task.resume()
    }

}
